#include "information.h"
#include "ui_information.h"

Information::Information(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Information)
{
    ui->setupUi(this);

    //正则表达式校验，限制输入
    ui->lineEdit_age->setValidator(new QRegExpValidator(QRegExp("^([1-9][0-9]{0,3})$")));
    ui->lineEdit_phone->setValidator(new QRegExpValidator(QRegExp("^\\d{13}$")));
    ui->lineEdit_id->setValidator(new QRegExpValidator(QRegExp("^\\d{17}[0-9Xx]$")));


}

Information::~Information()
{
    delete ui;
}

void Information::on_pushButton_edit_clicked()
{
    //切换为可编辑状态
    ui->lineEdit_name->setEnabled(true);
    ui->lineEdit_phone->setEnabled(true);
    ui->comboBox_sex->setEnabled(true);
    ui->lineEdit_age->setEnabled(true);
    ui->lineEdit_id->setEnabled(true);
    ui->pushButton_edit->setDisabled(true);
    ui->pushButton_confirm->setEnabled(true);
}

void Information::on_pushButton_confirm_clicked()
{
    //判断信息是否合法
    QRegExp phoneExp("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$");
    QRegExp idExp("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");
    if(ui->lineEdit_name->text().isEmpty()){
        QMessageBox::critical(this,"错误","请输入姓名！");
        return;
    }
    if(!phoneExp.exactMatch(ui->lineEdit_phone->text())){
        QMessageBox::critical(this,"错误","手机号格式输入错误！");
        return;
    }
    if(!idExp.exactMatch(ui->lineEdit_id->text())){
        QMessageBox::critical(this,"错误","身份证号格式输入错误！");
        return;
    }
    if(!checkIdNumber(ui->lineEdit_id->text())){
        QMessageBox::critical(this,"错误","身份证号校验失败！");
        return;
    }

    //切换为不可编辑状态
    ui->lineEdit_name->setEnabled(false);
    ui->lineEdit_phone->setEnabled(false);
    ui->comboBox_sex->setEnabled(false);
    ui->lineEdit_age->setEnabled(false);
    ui->lineEdit_id->setEnabled(false);
    ui->pushButton_edit->setDisabled(false);
    ui->pushButton_confirm->setEnabled(false);
}

bool Information::checkIdNumber(QString id)
{
    //校验身份证号
    const int w[]={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
    const char t[]={'1','0','X','9','8','7','6','5','4','3','2'};
    int sum=0;
    for(int i=0;i<17;i++)
        sum+=w[i]*QString(id[i]).toInt();
    return id[17]==t[sum%11];
}
